package com.epalmpay.controller.channel.order;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.epalmpay.entity.OrderServiceGood;
import com.epalmpay.entity.OrderServiceGoodDetail;
import com.epalmpay.mapper.OrderServiceGoodMapper;
import com.epalmpay.service.shop.IShopService;

import com.epalmpay.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.epalmpay.commom.BaseController;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.dto.system.PageDTO;
import com.epalmpay.dto.system.TradeOfflineBaseOutDTO;
import com.epalmpay.dto.order.OrderDetailOutDTO;
import com.epalmpay.dto.order.OrderInDTO;
import com.epalmpay.dto.order.OrderListOutDTO;
import com.epalmpay.dto.order.OrderOutDTO;
import com.epalmpay.entity.Page;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.operator.ISysLogService;
import com.epalmpay.service.order.IOrderService;
import com.epalmpay.util.Tools;

@Controller
@RequestMapping(value="/channel/order")
public class ServiceGoodController extends BaseController {
     
	@Resource  
    private IOrderService orderService;  
	@Resource 
	private ISysLogService sysLogService;
	@Resource
	private IShopService shopService;
	@Autowired 
    @Lazy
	private ITemplateMailSendService templateMailSendService;

	@Resource
	private OrderServiceGoodMapper orderServiceGoodMapper;
	/**
	 * 订单管理--获取服务商品订单列表
	 * 
	 */
	@RequestMapping(value="/servicegoodList")
	@ResponseBody
	public OrderListOutDTO  ServiceGoodList(OrderInDTO orderInDTO,PageDTO pageDTO){
		OrderListOutDTO orderListOutDTO = new OrderListOutDTO();
		try {
		
			Page page=Tools.pageEmtity(pageDTO);	
			
            //查询时取数据			
			if(orderInDTO.getIsReload()){
				//获取统计设备信息
				List<OrderOutDTO> orderOutDTOList = orderService.getServiceGoodList(orderInDTO, page);
				orderListOutDTO.setOrderOutDTOList(orderOutDTOList);
			}
			orderListOutDTO.setPage(page); 
			orderListOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
			return orderListOutDTO;
		} catch (ApplicationException ae) { 
			orderListOutDTO.setErrorCode(ae.errCode, ae.errMsg);
			ae.printStackTrace();
			logger.error(ae);
		}
		 catch (Exception e) { 
			 orderListOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
			logger.error(e);
		}
		return orderListOutDTO;
	}		

	/**
	 * 订单管理--服务商品订单详情
	 * 
	 */
	@RequestMapping(value="/servicegoodDetail")
	@ResponseBody
	public OrderDetailOutDTO  ServicegoodDetail(OrderInDTO orderInDTO){
		OrderDetailOutDTO orderDetailOutDTO = new OrderDetailOutDTO();
		try {
		    	//调用服务
			orderDetailOutDTO = orderService.getServiceGoodDetail(orderInDTO);
			orderDetailOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
			return orderDetailOutDTO;
		} catch (ApplicationException ae) { 
			orderDetailOutDTO.setErrorCode(ae.errCode, ae.errMsg);
			ae.printStackTrace();
			logger.error(ae);
		}
		 catch (Exception e) { 
			 orderDetailOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
			logger.error(e);
		}
		return orderDetailOutDTO;
	}		

	
	/**
	 * 订单管理  商城商品--服务商品订单确认退款
	 * 
	 */
	@RequestMapping(value="/servicegoodConfirmRefund")
	@ResponseBody
	public BaseOutDTO  ServicegoodConfirmRefund(OrderInDTO orderInDTO){
		BaseOutDTO baseOutDTO = new BaseOutDTO(); 
		try {
			TradeOfflineBaseOutDTO tradeOfflineOutDTO=orderService.editConfirmRefundServiceGoodOrder(orderInDTO);
			if(tradeOfflineOutDTO!=null&&tradeOfflineOutDTO.getErrorCode().equals(Rescode.SUCCESS)){
				
				//微信发送模板消息	 
    				try {
						templateMailSendService.sendTemplate(tradeOfflineOutDTO.getTradeOffline(),  BizEnum.WebTemplateType.template5.getType(),
								tradeOfflineOutDTO.getTradeOffline().getPayerId(),
								tradeOfflineOutDTO.getTradeOffline().getGroupId(), BizEnum.PaymentType.WebChat.getType(),ROOT_HOME_URL);
					} catch (Exception e) {
						logger.info ("模板消息发送失败"+e); 
					}
				
				 try {

					 if (orderInDTO.getOrderNo().startsWith(Const.CONSUMPTION_VIRTUAL)) {//如果订单编号前缀为服务商品订单前缀，表明是服务商品的退款
						 OrderServiceGood orderServiceGood = orderServiceGoodMapper.queryShopIdByOrderId(orderInDTO.getOrderNo());

						 baseOutDTO = orderService.updateRebatewithdraw(tradeOfflineOutDTO.getTradeOffline(), orderInDTO.getRefundAmount(), orderServiceGood.getShopId());

					 }
					 baseOutDTO.setErrorCode(Rescode.SUCCESS, "退款成功");
    	             return baseOutDTO;
				} catch (ApplicationException ae) { 
					baseOutDTO.setErrorCode(ae.errCode, ae.errMsg);
					baseOutDTO.setErrorCode(Rescode.SUCCESS, "退款成功"+ae.errMsg);
					ae.printStackTrace();
					logger.error(ae);
				}catch (Exception e) {
					baseOutDTO.setErrorCode(Rescode.SUCCESS, "退款成功,优惠福利未退回");
					e.printStackTrace();
					logger.error(e);
				  }
			  }
			baseOutDTO.setErrorCode(Rescode.FAIL, tradeOfflineOutDTO.getErrorMsg());
			return baseOutDTO;
		} catch (ApplicationException ae) { 
			baseOutDTO.setErrorCode(ae.errCode, ae.errMsg);
			ae.printStackTrace();
			logger.error(ae);
		}
		 catch (Exception e) { 
			baseOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
			logger.error(e);
		}
		return baseOutDTO;
	}		
		
	
	/**
	 * 订单管理--服务商品关闭订单  ???
	 * 
	 */
	@RequestMapping(value="/servicegoodCloseOrder")
	@ResponseBody
	public OrderListOutDTO  ServicegoodCloseOrder(OrderInDTO orderInDTO){
		OrderListOutDTO orderListOutDTO = new OrderListOutDTO();
		try {

            //查询时取数据
			//if(orderInDTO.getIsReload()){
				//调用服务
//				orderService.editConfirmRefundServiceGoodOrder(orderInDTO);
			//}

			orderService.updateOrderServiceGood(orderInDTO);
			orderListOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");

			String content ="关闭服务订单";
			sysLogService.addSysLog(orderInDTO.getUserId(),orderInDTO.getUserName(),null,content,orderInDTO.getGroupId());//(Long userId,String ip,String content,Long groupId

			return orderListOutDTO;
		} catch (ApplicationException ae) {
			orderListOutDTO.setErrorCode(ae.errCode, ae.errMsg);
			ae.printStackTrace();
			logger.error(ae);
		}
		 catch (Exception e) {
			 orderListOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
			logger.error(e);
		}
		return orderListOutDTO;
	}

	/**
	 * 服务商品对账汇总
	 *
	 *
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public List  ServicegoodList(){
		Map map = new HashMap();
		map.put("groupId",getRequest().getParameter("groupid"));
		map.put("searchkey",getRequest().getParameter("searchkey"));
		map.put("couponstatus",getRequest().getParameter("couponstatus"));
		map.put("transactionstatus", getRequest().getParameter("transactionstatus"));
		List result = orderService.selectServiceGoodByMonth(map);
		return result;
	}

	/**
	 * 服务商品对账月明细
	 *
	 */
	@RequestMapping(value="/monthlist")
	@ResponseBody
	public List ServicegoodMonthList(){
		Map map = new HashMap();
		map.put("groupId",getRequest().getParameter("groupid"));
		map.put("searchkey",getRequest().getParameter("searchkey"));
		map.put("couponstatus",getRequest().getParameter("couponstatus"));
		List result = orderService.selectServiceGoodByMonthList(map);
		for(int i=0;i<result.size();i++) {
			Map m = (Map) result.get(i);
			if(m.get("shop_id") != null) {
				m.put("receiver_name", shopService.getShopDetailById(Long.parseLong(m.get("shop_id").toString())).get("shopName").toString());
			} else {
				m.put("receiver_name", "无");
			}
		}
		return result;
	}

	/**
	 * 服务商品对账日明细
	 *
	 */
	@RequestMapping(value="/daylist")
	@ResponseBody
	public List  ServicegoodDayList(){
		Map map = new HashMap();
		map.put("groupId",getRequest().getParameter("groupid"));
		map.put("searchkey",getRequest().getParameter("searchkey"));
		map.put("couponstatus",getRequest().getParameter("couponstatus"));
		List result = orderService.selectServiceGoodByDay(map);
		for(int i=0;i<result.size();i++) {
			Map m = (Map) result.get(i);
			if(m.get("shop_id") != null) {
				m.put("receiver_name", shopService.getShopDetailById(Long.parseLong(m.get("shop_id").toString())).get("shopName").toString());
			} else {
				m.put("receiver_name", "无");
			}
		}
		return result;
	}

	/**
	 * 根据二维码code查询订单信息
	 * @return
	 */
	@RequestMapping(value="/getGoodOrderByCode")
	@ResponseBody
	public Map getGoodOrderByCode() {
		Map result = new HashMap();

		String code = getRequest().getParameter("qrcode");
		String groupid = getRequest().getParameter("groupid");
		try {
			Map param = new HashMap();
			param.put("couponCode", code);
			param.put("groupId", groupid);
			OrderServiceGoodDetail osgd = orderService.getServiceGoodDetailByCode(param);
			if(osgd != null) {
				result.put("result", osgd);
				result.put("code", "000000");
			} else {
				result.put("code", "000001");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
